package DDD.RPCDemo1.src.cn.tedu.calc;


import DDD.RPCDemo1.src.cn.tedu.rpc.RPCReq;
import DDD.RPCDemo1.src.cn.tedu.utils.NIOUtils;
import DDD.RPCDemo1.src.cn.tedu.utils.SeriaUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CalcProxy {

    private CalcProxy() {
    }

    public static CalcIntf getCalc(){
        return (CalcIntf) Proxy.newProxyInstance(CalcIntf.class.getClassLoader(), new Class[]{CalcIntf.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                RPCReq req = new RPCReq("cn.tedu.calc.CalcImpl",method.getName(),method.getParameterTypes(),args);
                byte[] bytes = SeriaUtils.Obj2Bytes(req);
                byte[] retBytes = NIOUtils.call(bytes);
                Object ret = SeriaUtils.Bytes2Obj(method.getReturnType(),retBytes);
                return method.getReturnType().cast(ret);
            }
        });
    }

}
